<template>
  <div>
    <el-dialog
      :title="titleText"
      :visible="showDialog"
      width="30%"
      @close="onclose"
    >
      <el-form ref="addForm" :rules="addFormRules" :model="form" label-width="100px">
        <el-form-item prop="name" label="部门名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item prop="code" label="部门编码">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item prop="manager" label="部门负责人">
          <el-select v-model="form.manager" :loading="isLoading" loading-text="正在加载中..." placeholder="请选择活动区域" @focus="loadEmployeesList">
            <el-option v-for="item in employeesList" :key="item.id" :label="item.username" :value="item.username" />
          </el-select>
        </el-form-item>
        <el-form-item prop="introduce" label="部门介绍">
          <el-input v-model="form.introduce" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onclose">取 消</el-button>
        <el-button type="primary" @click="addDepartment">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeesList } from '@/api/employees.js'
import { addDepartments, getDepartments, updateDepartments } from '@/api/departments.js'
export default {
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    row: {
      type: Object,
      required: true
    }
  },

  data() {
    // 检验部门名称是否重复
    const checkDeptNameisRepeat = async(rule, value, callback) => {
      let isRepeat
      if (this.form.id) {
        // 编辑
        const { depts } = await getDepartments()
        const slibings = depts.filter((item) => (item.id !== this.row.id && item.pid === this.row.pid))
        isRepeat = slibings.some(item => item.name === value)
      } else {
        // 添加
        isRepeat = this.row.children && this.row.children.some(item => item.name === value)
      }
      return isRepeat ? callback(new Error('部门已存在')) : callback()
    }
    // 检验部门编码是否重复
    const checkDeptCodeisRepeat = async(rule, value, callback) => {
      const res = await getDepartments()
      let isRepeat
      if (this.form.id) {
        // 编辑
        isRepeat = res.depts.some(item => (item.code !== this.row.code && item.code === value))
      } else {
        // 添加
        isRepeat = res.depts.some(item => item.code === value)
      }
      return isRepeat ? callback(new Error('部门已存在')) : callback()
    }
    return {
      form: {
        code: '', // 部门编码
        introduce: '', // 介绍
        manager: '', // 负责人名称
        name: '' // 部门名称
      },
      addFormRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '部门名称要求2-50个字符', trigger: 'blur' },
          { validator: checkDeptNameisRepeat, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '部门编码要求2-50个字符', trigger: 'blur' },
          { validator: checkDeptCodeisRepeat, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { trigger: 'blur', min: 2, max: 300, message: '部门介绍要求2-300个字符' }
        ]
      },
      employeesList: [], // 员工列表
      isLoading: false
    }
  },

  computed: {
    titleText() {
      return (this.form.id ? '编辑' : '添加') + '部门'
    }
  },

  created() {

  },

  methods: {
    // 关闭弹窗
    onclose() {
      // 重置表单
      this.$refs.addForm.resetFields()
      this.$emit('update:show-dialog', false)
      // 编辑和添加弹窗在取消时有动画，如果马上重置有一个修改title的效果，所以等弹窗关闭时在重置
      setTimeout(() => {
        // 为了避免编辑和添加时数据的不同，而重置(初始化)
        this.form = {
          code: '',
          introduce: '',
          manager: '',
          name: ''
        }
      }, 200)
    },

    // 获取员工简单列表（负责人列表）
    async loadEmployeesList() {
      // 开启loading
      this.isLoading = true
      const res = await getEmployeesList()
      this.employeesList = res
      // 关闭loading
      this.isLoading = false
    },

    // 添加部门
    async addDepartment() {
      try {
        await this.$refs.addForm.validate()
        if (this.form.id) {
          // 编辑
          const { id, code, introduce, manager, name } = this.form
          await updateDepartments({
            id,
            code,
            introduce,
            manager,
            name
          })
          this.$message.success('修改成功')
        } else {
          // 添加
          // 父id
          this.form.pid = this.row.id || ''
          await addDepartments(this.form)
          this.$message.success('添加成功')
        }
        this.$emit('add-success')
        this.onclose()
      } catch (error) {
        console.log(error)
      }
    },

    // 给表单赋值
    setForm() {
      // 深拷贝
      this.form = JSON.parse(JSON.stringify(this.row))
    }
  }
}
</script>

<style scoped>

</style>
